package kitex

import (
	"log"

	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"gopkg.in/yaml.v2"
)

// 泛型标识结构体
func GetRemoteConfig[T any](config NacosConfig, param *T) error {
	param = new(T)
	// 配置nacos clientconfig
	var clientConfig = constant.ClientConfig{
		NamespaceId:         config.Client.NamespaceId, // 如果需要支持多namespace，我们可以创建多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           config.Client.TimeoutMs,
		NotLoadCacheAtStart: config.Client.NotLoadCacheAtStart,
		LogDir:              config.Client.LogDir,
		CacheDir:            config.Client.CacheDir,
		LogLevel:            config.Client.LogLevel,
		Username:            config.Client.Username,
		Password:            config.Client.Password,
	}

	// 至少一个ServerConfig
	var serverConfigs = []constant.ServerConfig{
		{
			IpAddr:      config.Server.IpAddr,
			ContextPath: config.Server.ContextPath,
			Port:        config.Server.Port,
			Scheme:      config.Server.Scheme,
		},
	}

	// 创建动态配置客户端的另一种方式 (推荐)
	var configClient, err = clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		log.Println("创建nacos配置客户端失败！")
		return err
	}

	// 获取配置信息
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: config.Param.DataId,
		Group:  config.Param.Group,
	})
	if err != nil {
		log.Println("naocs获取动态配置失败！")
		return err
	}

	// yaml解析
	err = yaml.Unmarshal([]byte(content), param)
	if err != nil {
		log.Println("yaml解析配置失败！")
		return err
	}
	return nil
}

func DeafultNacosConfig(username, password, namespaceId, ipAddr, scheme string, port uint64, dataId, group string) NacosConfig {
	return NacosConfig{
		Client: ClientConfig{
			NamespaceId:         namespaceId,
			TimeoutMs:           5000,
			NotLoadCacheAtStart: true,
			LogDir:              "tmp/nacos/log",
			CacheDir:            "tmp/nacos/cache",
			LogLevel:            "debug",
			Username:            username,
			Password:            password,
		},
		Server: ServerConfig{
			IpAddr:      ipAddr,
			Port:        port,
			Scheme:      scheme,
			ContextPath: "/nacos",
		},
		Param: ClientParam{
			DataId: dataId,
			Group:  group,
		},
	}
}
